import router from '@/router'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store'
const whiteList = ['/login', '/404', '/Project-Bintan']

router.beforeEach(async(to, from, next) => {
  nprogress.start()

  try {
    if (store.getters.token) {
      // 如果要访问的是登录页，重定向到首页
      if (to.path === '/login') {
        next('/')
        nprogress.done()
        return
      }

      // 如果还没有获取用户信息，先获取用户信息
      if (store.getters.userInfo.length === 0) {
        try {
          const menus = await store.dispatch('user/getUserInfo')
          const routes = await store.dispatch('permission/filterRoutes', menus)

          // 添加动态路由
          router.addRoutes([
            ...routes,
            { path: '*', redirect: '/404', hidden: true }
          ])

          // 检查是否需要修改密码
          if (
            store.getters.needChangePassword &&
            to.name !== '/Admin/ChangePassword/Index'
          ) {
            next({ name: '/Admin/ChangePassword/Index', replace: true })
          } else {
            // 如果是直接访问的路由，需要重新进入一次
            next({ ...to, replace: true })
          }
        } catch (error) {
          console.error('权限获取失败:', error)
          await store.dispatch('user/logout')
          next('/login')
          nprogress.done()
        }
      } else {
        // 已经有用户信息了
        if (
          store.getters.needChangePassword &&
          to.name !== '/Admin/ChangePassword/Index'
        ) {
          next({ name: '/Admin/ChangePassword/Index', replace: true })
        } else {
          next()
        }
      }
    } else {
      // 没有token的处理逻辑保持不变
      if (whiteList.includes(to.path)) {
        next()
      } else {
        next('/login')
        nprogress.done()
      }
    }
  } catch (error) {
    console.error('路由守卫错误:', error)
    nprogress.done()
  }
})

/** *
 * 后置守卫
 * **/
router.afterEach(() => {
  nprogress.done()
})
